package com.journaldev.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.journaldev.spring.model.PersonalOffice;
import com.journaldev.spring.service.PersonalOfficeService;

@Controller
public class PersonalOfficeController {
	
	private PersonalOfficeService officeService;

	@Autowired(required=true)
	@Qualifier(value="officeService")
	public void setOfficeService(PersonalOfficeService officeService) {
		this.officeService = officeService;
	}
	
	@RequestMapping(value = {"/offices"}, method = RequestMethod.GET)
	public String listOffice(Model model) {
		model.addAttribute("office", new PersonalOffice());
		model.addAttribute("listOffice", this.officeService.listOffice());
		return "office";
	}
	
	@RequestMapping(value = {"/office/add"}, method = RequestMethod.POST)
	public String addOffice(@ModelAttribute("office") PersonalOffice p,  BindingResult result, Model model, RedirectAttributes redirectAttrs) {
		if(result.hasErrors()) {
			model.addAttribute("message", "add errors");
			return "redirect:/offices";
		}
		if(p.getId() != 0) {
			this.officeService.updateOffice(p);
			redirectAttrs.addFlashAttribute("message", "update success id =" + p.getId());
		} else {
			this.officeService.addOffice(p);
			redirectAttrs.addFlashAttribute("message", "add success");
		}
		model.asMap().clear();
		return "redirect:/offices";
	}
	
	@RequestMapping(value = {"/office/remove/{id}"})
	public String removeOffice(@PathVariable("id") int id) {
		this.officeService.removeOffice(id);
		return "redirect:/offices";
	}
	
	@RequestMapping("/office/edit/{id}")
    public String editOffice(@PathVariable("id") int id, Model model){
        model.addAttribute("office", this.officeService.getOfficeById(id));
        model.addAttribute("listOffice", this.officeService.listOffice());
        return "office";
    }

}
